<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchCreateFaceCheckConfig, fetchUpdateFaceCheckConfig } from '@/service/api/business/face-check-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'FaceCheckConfigOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.FaceCheckConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const { loading: submitLoading, startLoading, endLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增人脸核验配置',
    edit: '编辑人脸核验配置'
  };
  return titles[props.operateType];
});

// 活体检测类型选项
const livingTypeOptions = ref([
  { label: '远近', value: 1 },
  { label: '眨眼', value: 2 },
  { label: '摇头', value: 3 },
  { label: '点头', value: 4 },
  { label: '张嘴', value: 5 },
  { label: '炫彩', value: 6 }
]);

// 表单模型 - 使用数组类型用于多选
const formModel = reactive({
  id: '',
  livingType: [] as number[], // 表单中使用数组类型
  returnUrl: '',
  status: 0
});

type RuleKey = keyof typeof formModel;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  livingType: createRequiredRule('检测类型不能为空'),
  returnUrl: [
    createRequiredRule('回调地址不能为空'),
    {
      pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/,
      message: '请输入有效的URL地址',
      trigger: ['blur', 'change']
    }
  ],
  status: createRequiredRule('状态不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    // 重置表单
    formModel.id = '';
    formModel.livingType = [];
    formModel.returnUrl = '';
    formModel.status = 0;
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    // 将数字类型的livingType转换为数组
    const rowData = props.rowData;
    formModel.id = rowData.id || '';
    formModel.returnUrl = rowData.returnUrl || '';
    formModel.status = rowData.status || 0;

    // 将数字转换为数组，例如 26 -> [2, 6]
    if (rowData.livingType) {
      formModel.livingType = String(rowData.livingType).split('').map(Number);
    } else {
      formModel.livingType = [];
    }
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startLoading();

  // 准备提交数据，将数组类型的livingType转换为数字
  const livingTypeValue = formModel.livingType.length > 0
    ? Number(formModel.livingType.join(''))
    : 0;

  const submitData: Api.Business.FaceCheckConfigOperateParams = {
    id: formModel.id,
    livingType: livingTypeValue,
    returnUrl: formModel.returnUrl,
    status: formModel.status
  };

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateFaceCheckConfig(submitData);
    if (error) {
      endLoading();
      return;
    }
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateFaceCheckConfig(submitData);
    if (error) {
      endLoading();
      return;
    }
  }

  endLoading();
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="600" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="formModel" :rules="rules">
        <NDivider>基本信息</NDivider>
        <NFormItem label="检测类型" path="livingType">
          <NSelect
            v-model:value="formModel.livingType"
            multiple
            :options="livingTypeOptions"
            placeholder="请选择检测类型"
          />
          <template #feedback>
            <div class="text-xs text-gray-500">支持多种活体方式组合检测，例如：26，表示先眨眼再炫彩</div>
          </template>
        </NFormItem>
        <NFormItem label="回调地址" path="returnUrl">
          <NInput v-model:value="formModel.returnUrl" placeholder="请输入回调地址" />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <DictRadio v-model:value="formModel.status" dict-code="sys_normal_disable" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
